﻿using System;

using dotMath;

namespace Soulver.Model
{
    public static class ExpressionCompiler
    {
        private static EqCompiler compiler;

        public static void AddVariable(string key, double value)
        {
            InitializeCompiler();

            compiler.SetVariable(key, value);
        }
        
        public static bool IsMatch(string s)
        {
            InitializeCompiler();

            try
            {
                compiler.SetFunction(s);
                compiler.Compile();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static string Parse(string s)
        {
            InitializeCompiler();

            compiler.SetFunction(s);

            try
            {
                return compiler.Calculate().ToString();
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }

        public static void Reset()
        {
            compiler = new EqCompiler(true);
        }

        private static void InitializeCompiler()
        {
            if (compiler == null)
                compiler = new EqCompiler(true);
        }
    }
}